#!/usr/bin/env Rscript
args = commandArgs(trailingOnly=TRUE)

source("cueing_functions.R")

# Set up data for use with ASA standard errors
x <- read.csv(paste0("cueing_data1616splitweighted.csv"))
x$deltay <- (x$agree2 - x$agree1)

x$legA2 <- apply(x, 1, function(z) paste0(z[16], z[7]))
x$legB2 <- apply(x, 1, function(z) paste0(z[17], z[7]))

Aind <- which(colnames(x) == "legA2")
Bind <- which(colnames(x) == "legB2")

x$dyads <- apply(x, 1, function(r) paste0(r[Aind], "-", r[Bind]))

# Model is here 
fmla <- formula(deltay ~ treat + cs +
                  I(treat * copartisans) + 
                  I(treat * cs) + 
                  I(cs * copartisans) + 
                  sgcs + I(treat * sgcs) +
                  ogcs + I(treat * ogcs) + 
                  sfcs + I(treat * sfcs) + 
                  ofcs + I(treat * ofcs) +
                  interaction(factor(congress), committee,
                              leg_party, copartisans) + 
                  n1 + n2)

fit <- lm(fmla, data = x, weights = x$weights)
coef(fit)[1:14]
coef(fit)[1:14]/sqrt(diag(vcov(fit))[1:14])

index <- unique(c(as.character(x$legA2), as.character(x$legB2)))

dyad.mat <- apply(x[,c(Aind, Bind)], 2, as.character)

## You will need access to a cluster computer to calculate the standard errors
cl <- makeCluster(32)
registerDoSNOW(cl)
dyad.vcov <- dyad.robust.se(x, fit, index, dyad.mat)

fit <- lm(fmla, data = x, weights = x$weights, qr = FALSE)

fmla <- formula(deltay ~ treat + cs +
                  I(treat * copartisans) + 
                  I(treat * cs * copartisans) + 
                  I(treat * cs * (1-copartisans)) +
                  I(cs * copartisans) + 
                  sgcs + I(treat * sgcs) +
                  ogcs + I(treat * ogcs) + 
                  sfcs + I(treat * sfcs) + 
                  ofcs + I(treat * ofcs) +
                  interaction(factor(congress), committee,
                              leg_party, copartisans) + 
                  n1 + n2)

part_fit <- lm(fmla, data = x, weights = x$weights)
part_dyad.vcov <- dyad.robust.se(x, part_fit, index, dyad.mat)

# Store with qr = FALSE to save memory
part_fit <- lm(fmla, data = x, weights = x$weights, qr = FALSE)
stopCluster(cl)

save.image(paste0("cueingresults_cont.RData"))
